﻿using System;
using System.Security.Permissions;
using Castle.MonoRail.Framework;
using Hadlow.Jobvertizer.Repositories;
using Hadlow.Jobvertizer.Models;
using System.Collections;
using Hadlow.Jobvertizer.HtmlHelpers;
using NHibernate.Expression;

namespace Hadlow.Jobvertizer.Controllers
{
    [Scaffolding(typeof(Job))]
    public class JobController : BaseController
    {
        IJobRepository jobRepository;
        ILocationRepository locationRepository;
        IPosterRepository posterRepository;
        IRepository<Salary> salaryRepository;
        ISecurityHelper securityHelper;

        public JobController(
            IJobRepository jobRepository,
            ILocationRepository locationRepository,
            IPosterRepository posterRepository,
            IRepository<Salary> salaryRepository,
            ISecurityHelper securityHelper)
        {
            this.jobRepository = jobRepository;
            this.locationRepository = locationRepository;
            this.posterRepository = posterRepository;
            this.salaryRepository = salaryRepository;
            this.securityHelper = securityHelper;
        }


        public void JobForm([DataBind("job")] Job job)
        {
            // if no job is supplied, create a new one to hold the current poster
            if (job == null)
            {
                job = new Job();
            }

            if (job.Id != 0)
            {
                job = jobRepository.GetById(job.Id);
            }
            else
            {
                securityHelper.Context = Context;
                job.Poster = posterRepository.GetPosterFor(securityHelper.CurrentUser); 
            }

            PropertyBag.Add("location", locationRepository.GetTopLevelLocation());
            PropertyBag.Add("salaries", salaryRepository.GetAll());

            // need to work out how monorail provides these helpers automatically to the view engine.
            PropertyBag.Add("hierarchicalSelect", new HierarchicalSelect());

            PropertyBag.Add("job", job);
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Poster")]
        public void AddJob([DataBind("job")] Job job)
        {
            bool isNewJob = (job.Id == 0);

            jobRepository.Save(job);
            
            // refresh the job from the database so that all it's properties display correctly on the summary
            if (isNewJob)
            {
                jobRepository.Refresh(job);
            }
            else
            {
                job = jobRepository.GetById(job.Id);
            }

            PropertyBag.Add("job", job);
        }
    }
}
